package com.building.hcrm.ui;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.building.hcrm.R;
import com.building.hcrm.R.id;
import com.building.hcrm.base.BaseActivity;
import com.building.hcrm.base.BaseAsyncTask;
import com.building.hcrm.base.BaseParam;
import com.building.hcrm.base.BaseStaffSelector.SelectedStaffListener;
import com.building.hcrm.common.ComConst;
import com.building.hcrm.common.ComFunc;
import com.building.hcrm.common.User;
import com.building.hcrm.model.Achievements;
import com.building.hcrm.model.AchmetLog;
import com.building.hcrm.model.PlanDetail;
import com.building.hcrm.model.SysUser;
import com.building.hcrm.ui.customcontrols.ComStaffSelector;
import com.building.hcrm.wcf.KpiServiceProxy;
import com.building.hcrm.wcf.TaskServiceProxy;

public class KpiEditActivity extends BaseActivity
{
	private int iCount = 0;
	private ComStaffSelector _selector;
	private ListView _listView;
	private Button _btnDate;
	private Button _btnSave;
	private ImageButton _imgBtnTitleRight;

	private HashMap<String,Object> _model;
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_kpi_edit);
		InitTitle();
		_selector = (ComStaffSelector) findViewById(R.id.staff_selector);
		Serializable data = getIntent().getSerializableExtra(
				ComConst.INTENT_EXTRA_SYSUSER);
		if (data != null) {
			_selector.load(ComStaffSelector.DISPLAY_TYPE_ALL, (SysUser)data);
		} else {
			_selector.load(ComStaffSelector.DISPLAY_TYPE_ALL, User.getInstance(this));
		}
		_model = (HashMap<String,Object>)getIntent().getSerializableExtra("AchmetIns");
		_listView = (ListView) findViewById(R.id.list_kpi_add);
		_btnSave = (Button) findViewById(R.id.btn_kpi_add);
		_btnSave.setOnClickListener(SaveClickListener);
		setDate((Date)_model.get("Time"));
		setListView((List<AchmetLog>)_model.get("AchmetLogList"));
	}

	private void InitTitle()
	{
		imgbtnHome = (ImageButton) findViewById(id.imgbtn_home);
		imgbtnHome.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				finish();
			}
		});
		setTitle(getString(R.string.kpi_edit_title));
		_imgBtnTitleRight = (ImageButton) findViewById(R.id.imgbtn_save);
		_imgBtnTitleRight.setVisibility(View.INVISIBLE);
	}
	
	private void setDate(Date dt)
	{
		try
		{
			_btnDate = (Button) findViewById(R.id.btn_kpi_date);
			Calendar calendar = Calendar.getInstance();
			SimpleDateFormat sdfdate;
			sdfdate = new SimpleDateFormat(ComConst.DATE_FORMAT, Locale.getDefault());
			_btnDate.setText(sdfdate.format(dt == null ? calendar.getTime() : dt));
			registerDateClick(_btnDate);
		}
		catch (Exception e)
		{
			Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
		}
	}

	private void setListView(List<AchmetLog> param)
	{
		List<HashMap<String, Object>> lstHM = new ArrayList<HashMap<String, Object>>();
		if (null != param)
		{
			for (AchmetLog item : param)
			{
				HashMap<String, Object> hashMap = new HashMap<String, Object>();

				hashMap.put("kpiContent", item.AchtContent);
				hashMap.put("kpiScore", item.AchmetScore);
				hashMap.put("item", item);
				lstHM.add(hashMap);
			}
		}
		SimpleAdapter sAdapter = new SimpleAdapter(this, lstHM, R.layout.list_item_kpi_edit,
				new String[] { "kpiContent","kpiScore" }, new int[] { R.id.txtKpiItem ,R.id.txtKpiScore});

		_listView.setAdapter(sAdapter);
	}

	private View.OnClickListener SaveClickListener = new View.OnClickListener()
	{
		@SuppressWarnings("unchecked")
		@Override
		public void onClick(View v)
		{
			List<AchmetLog> lstAch = new ArrayList<AchmetLog>();
			Date dtCreate = ComFunc.GetDateByString(_btnDate.getText().toString(), ComConst.DATE_FORMAT);
			String strCheckUserName = User.getInstance(getApplicationContext()).getUserName();
			String strCheckUserNum = User.getInstance(getApplicationContext()).getUserNum();
			String strAchUserName = _selector.getCurrentStaff().getUserName();
			String strAchUserNum = _selector.getCurrentStaff().getUserNum();
			int nCount = _listView.getCount();
			for (int i = 0; i < nCount; i++)
			{
				EditText et = (EditText)_listView.getChildAt(i).findViewById(R.id.txtKpiScore);
				if(et.getText().toString().length()==0)
				{
					continue;
				}
				HashMap<String, Object> hm = (HashMap<String, Object>) _listView.getItemAtPosition(i);
				Achievements item = (Achievements)hm.get("item");
				
				Float f = Float.valueOf(et.getText().toString());
				if(f.compareTo(Float.valueOf(10)) > 0)
				{
					Toast.makeText(KpiEditActivity.this, item.AchtContent + "，打分超过10，请核对！", Toast.LENGTH_SHORT).show();
					return;
				}
				
				AchmetLog ach = new AchmetLog();
				ach.AchmetTime = dtCreate;
				ach.AchtID = item.AchtID;
				ach.AchmetScore =f;
				ach.AchtContent = item.AchtContent;
				ach.AchmetUserName = strAchUserName;
				ach.AchmetUserNum = strAchUserNum;
				ach.CheckUserName = strCheckUserName;
				ach.CheckUserNum = strCheckUserNum;
				lstAch.add(ach);
			}

			new BaseAsyncTask<List<AchmetLog>, String, Boolean>(KpiEditActivity.this, "提交...")
			{
				@Override
				protected void onPreExecute()
				{
					super.onPreExecute();
				}

				@Override
				protected Boolean doInBackground(List<AchmetLog>... params)
				{
					Boolean re = false;
					if (null != params && params.length > 0)
					{
						try
						{
							re = KpiServiceProxy.getInstance(getApplicationContext()).AchmetLogSet(params[0]);
						}
						catch (Exception e)
						{
							Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
						}
					}
					return re;
				}

				@Override
				protected void onPostExecute(Boolean result)
				{
					super.onPostExecute(result);
					if (result)
					{
						Toast.makeText(KpiEditActivity.this, "提交成功！", Toast.LENGTH_SHORT).show();
					}
					else
					{
						Toast.makeText(KpiEditActivity.this, "提交失败！", Toast.LENGTH_SHORT).show();
					}
				}
			}.execute(lstAch);
		}
	};
}
